package com.leps.nq.bu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leps.nq.bu.entity.BuTeam;
import com.leps.nq.bu.entity.BuTeamCust;
import com.leps.nq.bu.mapper.BuTeamCustMapper;
import com.leps.nq.bu.mapper.BuTeamMapper;
import com.leps.nq.bu.service.IBuTeamService;
import com.leps.nq.bu.vo.CreateTeamVo;
import com.leps.nq.bu.vo.TeamVo;
import com.leps.nq.bu.vo.UpdateTeamVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 任务队伍表 服务实现类
 * </p>
 *
 * @author hex
 * @since 2022-05-22
 */
@Service
public class BuTeamServiceImpl extends ServiceImpl<BuTeamMapper, BuTeam> implements IBuTeamService {

    @Autowired
    private BuTeamMapper teamMapper;
    @Autowired
    private BuTeamCustMapper teamCustMapper;

    @Override
    @Transactional
    public boolean saveWithMembers(CreateTeamVo createTeamVo) {
        BuTeam team = BeanUtil.toBean(createTeamVo, BuTeam.class);
        this.teamMapper.insert(team);
        List<Integer> custIds = createTeamVo.getCustIds();
        if (custIds != null) {
            final int teamId = team.getTeamId();
            for (Integer custId : custIds) {
                BuTeamCust teamCust = new BuTeamCust();
                teamCust.setTeamId(teamId);
                teamCust.setCustId(custId);
                this.teamCustMapper.insert(teamCust);
            }
        }
        return true;
    }

    @Override
    public TeamVo getTeamAndMemberInfo(Integer teamId) {
        return this.teamMapper.selectTeamAndMemberInfo(teamId);
    }

    @Override
    @Transactional
    public boolean updateTeamAndMember(UpdateTeamVo vo) {
        BuTeam team = BeanUtil.toBean(vo, BuTeam.class);
        this.teamMapper.updateById(team);
        this.teamCustMapper.deleteByTeamIds(Arrays.asList(team.getTeamId()));
        List<Integer> custIds = vo.getCustIds();
        if(ObjectUtil.isNotEmpty(custIds)) {
            for (Integer custId : custIds) {
                BuTeamCust teamCust = new BuTeamCust();
                teamCust.setCustId(custId);
                teamCust.setTeamId(team.getTeamId());
                this.teamCustMapper.insert(teamCust);
            }
        }
        return true;
    }

    @Override
    public List<TeamVo> listVo() {
        return this.teamMapper.selectTeamAndMemberNamesString();
    }

    @Override
    @Transactional
    public boolean removeBatchByIds(Collection<?> list) {
        this.teamCustMapper.deleteByTeamIds(list);
        super.removeBatchByIds(list);
        return true;
    }
}
